package web;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");      // 隐藏input属性的标记
        System.out.println("BaseServlet方法进入");
        System.out.println(req.getHeaderNames());
        System.out.println(req.getParameter("userNum"));
        System.out.println(req.getParameter("userName"));


        System.out.println(action);

        // 修改编码格式
        req.setCharacterEncoding("UTF-8");		// 接受到的
        resp.setContentType("text/html; charset=UTF-8");		// 修改发送的


        try {
            // 鉴别action, 获取相应的，方法反射对象
            Method method;
            if(ServletFileUpload.isMultipartContent(req)) {
                // 创建 FileItemFactory 工厂实现类
                FileItemFactory fileItemFactory = new DiskFileItemFactory();
                // 创建用于 解析 上传数据 的工具类 ServletFileUpload 类
                ServletFileUpload servletFileUpload1 = new ServletFileUpload(fileItemFactory);

                List<FileItem> list = servletFileUpload1.parseRequest(req);
                for(FileItem fileItem : list) {
                    if("action".equals( fileItem.getFieldName()))   action = fileItem.getString("UTF-8");
                }
                System.out.println(list);
                method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            } else {
                method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            }
            // 调用目标 方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
